package com.pwc.conversionTool.relation.xml;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

/**
 * dependency --dom4j
 * 
 * @author yuanhuang
 *
 */
public class XMLFactory {

	private Document document;

	/**
	 * 
	 * @param document
	 */
	public XMLFactory(Document document) {
		this.document = document;
	}

	public XMLFactory(String xmlString) throws DocumentException {
		SAXReader reader = new SAXReader();
		document = reader.read(new StringReader(xmlString));
	}

	/**
	 * 
	 * @return
	 */
	public XMLNode getRootNode() {
		Element root = document.getRootElement();

		XMLNode node = new XMLNode(root.getName(), root.getPath(), "");
		XMLNode resultNode = nodeWalk(document.getRootElement(), node);

		return resultNode;
	}

	/**
	 * 
	 * @param element
	 */
	private XMLNode nodeWalk(Element element, XMLNode node) {

		List<XMLNode> childrenList = new ArrayList<XMLNode>();
		// List<XMLNode> attributes=new ArrayList<XMLNode>();

		for (int i = 0, size = element.nodeCount(); i < size; i++) {
			Node domNode = element.node(i);
			if (domNode instanceof Element) {
				XMLNode thisNode = new XMLNode(domNode.getName(),
						domNode.getPath(), domNode.getText().trim());
				XMLNode childNode = nodeWalk((Element) domNode, thisNode);
				for (XMLNode xlmnode : attributesWalk((List<Node>) ((Element) domNode)
						.attributes()))
					childrenList.add(xlmnode);
				childrenList.add(childNode);

				System.out.println(domNode.getName());

			} else {
				// doing sth
			}
		}
		node.setChildren(childrenList);
		return node;
	}

	/**
	 * loop for attribute
	 * 
	 * @param attrList
	 * @return
	 */
	private List<XMLNode> attributesWalk(List<Node> attrList) {
		List<XMLNode> result = new ArrayList<XMLNode>();

		for (Node e : attrList) {
			result.add(new XMLNode(e.getName(), e.getPath(), e.getText().trim()));
		}

		return result;
	}

}
